import Notice from '../../../Models/notice';
const noticeEntity = new Notice();

export function getNotices(req, res, next) {
    const {  ...query } = req.body;
    query.receiverId = req.user._id;
    // query.status = 0;
    noticeEntity.getNotices(query, (err, notices, total, hasMore) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0, data: { list: notices, total, hasMore } });
    })
}

export function getNotice(req, res, next) {
    const {  ...query } = req.body;
    noticeEntity.getNotice(query, (err, notices) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json(notices);
    })
}

export function readNotice(req, res, next) {
    const { _id } = req.body;
    noticeEntity.updateNotice({_id, status: 1}, err => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0 });
    });
}

export function getNoticeNum(req, res, next) {
    const query = {
        type: {
            $in: ['like', 'cmt']
        },
        status: 0,
        receiverId: req.user._id
    }
    noticeEntity.getAllNotices(query, (err, notices = []) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        const all = notices.length;
        const liekNum = notices.filter(n=>n.type==='like').length;
        return res.status(200).json({ code: 0, data: {
            liekNum,
            cmtNum: all - liekNum
        } });
    });
}


export function updateNotice(req, res, next) {
    const {  ...notice } = req.body;
    const noticeEntity = new Notice();
    if (!notice._id) {
        noticeEntity.saveNotice(notice, err => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            return res.status(200).json({ code: 0 });
        });
    } else {
        noticeEntity.updateNotice(notice, err => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            return res.status(200).json({ code: 0 });
        });
    }
}

export function removeNotices(req, res, next) {
    const noticeIds = req.body.noticeIds;

    noticeEntity.removeNotices(noticeIds, (err, notice) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0 });
    });
}